I'm following a couple of Udemy tutorials online link1 link2 that create an Angular error interceptor file on the client side. I'm trying to understand how and when I would see a statement inside this file that looks like this with a nested error?
if (error.status === 400) {
if (error.error.errors) { // not sure why we would have a nested error inside error
throw error.error;
} else {
this.alertService.danger(error.error.message);
}
}
Here is the full file
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(private router: Router, private alertService: AlertService) {}
intercept(req: HttpRequest < any > , next: HttpHandler): Observable < HttpEvent < any >> {
return next.handle(req).pipe(
catchError(error => {
if (error) {
if (error.status === 400) {
if (error.error.errors) { // not sure why we would have a nested error?
throw error.error;
} else {
this.alertService.danger(error.error.message);
}
}
if (error.status === 401) {
this.alertService.danger(error.error.message);
}
if (error.status === 404) {
this.router.navigateByUrl('/not-found');
}
if (error.status === 500) {
const navigationExtras: NavigationExtras = {
state: {
error: error.error
}
};
this.router.navigateByUrl('/server-error', navigationExtras);
}
}
return throwError(error);
})
);
}
}
On the .Net server end I have controllers that return statements mostly like this:
return NotFound("Some message");
return BadRequest("Some message");
return Unauthorized("Some message");
return Ok();
I have gone through the API code, so when API will return this response (as body content)
{ errors: [], message: "" }
but not (which my comment was wrong):
{ error: { errors: [], message: "" } }
for error/exception cases. So the extra error is not from the API response.
Reference: ExceptionMiddleware
I believe the error is a HttpErrorResponse. And it has the error attribute.
class HttpErrorResponse extends HttpResponseBase implements Error {
constructor(init: { error?: any; headers?: HttpHeaders; status?: number; statusText?: string; url?: string; })
name: 'HttpErrorResponse'
message: string
error: any | null
ok: false
// inherited from common/http/HttpResponseBase
constructor(init: { headers?: HttpHeaders; status?: number; statusText?: string; url?: string; }, defaultStatus: number = 200, defaultStatusText: string = 'OK')
headers: HttpHeaders
status: number
statusText: string
url: string | null
ok: boolean
type: HttpEventType.Response | HttpEventType.ResponseHeader
}
Hence, to get the error body, you need:
error.error